/**
 * @class Event
 * @classdesc 底层事件类
 */
class Event {
    constructor() {
        this.event = {
            //eventname:[fn]
        };
    }
    //用户订阅，用户会发送一个event事件名和回调函数
    listen(name = 'select', fn) {
        if (Array.isArray(this.event[name])) {
            this.event[name].push(fn)
        } else {
            this.event[name] = []
            this.event[name].push(fn)
        }
    }
    once(name = 'select', fn) {
        if (fn) fn._once = true
        if (Array.isArray(this.event[name])) {
            this.event[name].push(fn)
        } else {
            this.event[name] = []
            this.event[name].push(fn)
        }
    }
    //系统发消息
    trigger(name = 'select', msg) {
        let index
        if (this.event[name]) {
            this.event[name].forEach((item, i) => {
                item.call(this, msg)
                if (item._once) {
                    index = i
                    this.event[name].splice(index, 1)
                }
            });
        } else {
            // console.warn(`select事件未注册`)
        }
    }
    unfollow(name = 'select', fn) {
        let ii
        if (this.event[name] && this.event[name].length > 0) {
            this.event[name].forEach((item, index) => {
                if (item === fn) {
                    ii = index
                }
            })
        }
        if (typeof ii === 'number') {
            this.event[name].splice(ii, 1)
        }
    }
    unfollowEventName(name) {
        this.event[name] = []
    }
}

export { Event }
